package org.mybatis.generator.api.plus;

import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangfupeng
 */
public class MybatisUtilLoginController {

    public static void writeLoginController(String basePackageName, String targeProject, String servicePackage) {
        File file = null;
        OutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            String packageNameFolder = basePackageName.replaceAll("\\.", "/");
            targeProject = targeProject.replaceAll("\\./","");
            File folder = new File(targeProject + "/" + packageNameFolder + "/controller/common/authorize");
            folder.mkdirs();
            file = new File(targeProject + "/" + packageNameFolder + "/controller/common/authorize/CommonLoginController.java");
            //如果文件不存在，则创建文件
            //file.deleteOnExit();
            file.createNewFile();
            fileOutputStream = new FileOutputStream(file);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "utf-8"));
            bufferedWriter.write("package " + basePackageName + ".controller.common.authorize;\n");
            bufferedWriter.write("\n");
            bufferedWriter.write("import " + basePackageName + ".aspect.Logging;\n");
            bufferedWriter.write("import " + basePackageName + ".bean.model.Admin;\n");
            bufferedWriter.write("import " + basePackageName + ".bean.model.AdminExample;\n");
            bufferedWriter.write("import " + servicePackage + ".AdminService;\n");
            bufferedWriter.write("import " + basePackageName + ".service.cache.CacheService;\n");
            bufferedWriter.write("import " + basePackageName + ".utils.JsonUtil;\n");
            bufferedWriter.write("import " + basePackageName + ".utils.NetworkUtil;\n");
            bufferedWriter.write("import " + basePackageName + ".utils.PasswordUtil;\n");
            bufferedWriter.write("import io.swagger.annotations.Api;\n");
            bufferedWriter.write("import io.swagger.annotations.ApiOperation;\n");
            bufferedWriter.write("import io.swagger.annotations.ApiParam;\n");
            bufferedWriter.write("import " + basePackageName + ".controller.response.SimpleResponse;\n");
            bufferedWriter.write("import org.slf4j.Logger;\n");
            bufferedWriter.write("import org.slf4j.LoggerFactory;\n");
            bufferedWriter.write("import org.springframework.beans.factory.annotation.Autowired;\n");
            bufferedWriter.write("import org.springframework.http.MediaType;\n");
            bufferedWriter.write("import org.springframework.web.bind.annotation.GetMapping;\n");
            bufferedWriter.write("import org.springframework.web.bind.annotation.RequestParam;\n");
            bufferedWriter.write("import org.springframework.web.bind.annotation.RequestMapping;\n");
            bufferedWriter.write("import org.springframework.web.bind.annotation.RestController;\n");
            bufferedWriter.write("\n");
            bufferedWriter.write("import javax.servlet.http.HttpServletRequest;\n");
            bufferedWriter.write("import java.util.HashMap;\n");
            bufferedWriter.write("import java.util.List;\n");
            bufferedWriter.write("import java.util.Map;\n");
            bufferedWriter.write("\n");
            bufferedWriter.write("@Api(description = \"脚手架自动生成的通用的管理员登陆\")\n");
            bufferedWriter.write("@RestController\n");
            bufferedWriter.write("@RequestMapping(value = \"/v1/common/admin\", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)\n");
            bufferedWriter.write("@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\n");
            //bufferedWriter.write("/** @author wangfupeng */\n");
            bufferedWriter.write("public class CommonLoginController implements Logging {\n");
            bufferedWriter.write("    public static final Logger logger = LoggerFactory.getLogger(CommonLoginController.class);\n");
            bufferedWriter.write("    @Autowired\n");
            bufferedWriter.write("    private AdminService adminService;\n");
            bufferedWriter.write("    @Autowired\n");
            bufferedWriter.write("    private CacheService cacheService;\n");
            bufferedWriter.write("\n");
            bufferedWriter.write("    @ApiOperation(\"登陆接口，改了这个接口地址，要记住改generatorConfig.xml里面的MybatisPluginHtml的loginUrl配置\")\n");
            bufferedWriter.write("    @GetMapping(value = \"/login\")\n");
            bufferedWriter.write("    public SimpleResponse login(\n");
            bufferedWriter.write("            @ApiParam(value = \"用户名\") @RequestParam(value = \"username\", required = true) String username,\n");
            bufferedWriter.write("            @ApiParam(value = \"密码\") @RequestParam(value = \"password\", required = true) String password,\n");
            bufferedWriter.write("            HttpServletRequest request\n");
            bufferedWriter.write("    ) {\n");
            bufferedWriter.write("        AdminExample adminExample = new AdminExample();\n");
            bufferedWriter.write("        adminExample.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);\n");
            bufferedWriter.write("        List<Admin> admins = adminService.list(adminExample);\n");
            bufferedWriter.write("        if (admins.isEmpty()) {\n");
            bufferedWriter.write("            return SimpleResponse.error(666151, \"用户名错误或者密码错误\");\n");
            bufferedWriter.write("        }\n");
            bufferedWriter.write("        Admin admin = admins.get(0);\n");
            bufferedWriter.write("        String token = PasswordUtil.generateToken();\n");
            bufferedWriter.write("        Map<String, Object> mapToken = new HashMap<>();\n");
            bufferedWriter.write("        mapToken.put(\"userId\", admin.getId());\n");
            bufferedWriter.write("        mapToken.put(\"username\", username);\n");
            bufferedWriter.write("        mapToken.put(\"token\", token);\n");
            bufferedWriter.write("        mapToken.put(\"ip\", NetworkUtil.getIpAddr(request));\n");
            bufferedWriter.write("        cacheService.set(\"password:\" + token, JsonUtil.toJson(mapToken));\n");
            bufferedWriter.write("        return SimpleResponse.success(mapToken);\n");
            bufferedWriter.write("    }\n");
            bufferedWriter.write("}\n");
            System.out.println("write to file success : "+file.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
